$(function () {
    /**
     * 1、弹出客户选择窗口:choose_customer_dialog是个table
     * 2、查询所有的客户信息:customer_datagrid
     * 3、选择客户
     * 4、回显数据，关闭选择窗口
     *
     */
    var choose_customer_dialog = $("#choose_customer_dialog");

    //设置选择客户对话枉的样式及按扭
    choose_customer_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#customer_btns2',
        closed: true,
        modal: true
    });

    var customer_datagrid = $("#customer_datagrid");
    //查询所有的客户信息
    customer_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        url: "/customer/selectAll.do",
        pagination: true,
        singleSelect: true,
        rownumbers: true,
        columns: [[
            {field: 'name', title: '客户名称', width: 70},
            {
                field: 'gender', title: '性别', width: 40, formatter: function (value) {
                    if (value == null) {
                        return '未知';
                    }
                    if (value) {
                        return '男';
                    }
                    if (!value) {
                        return '女';
                    }
                }
            },
            {field: 'tel', title: '电话', width: 100},
            {field: 'address', title: '地址', width: 100},
            {field: 'idcard', title: '身份证', width: 100}
        ]],
        onDblClickRow: function () {
            sure_customer();
        }
    });


    //汽车
    var choose_car_dialog = $("#choose_car_dialog");
    var car_datagrid = $("#car_datagrid");
    choose_car_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#car_btns2',
        closed: true,
        modal: true
    });
    //汽车分类下拉框
    $("#cartype").combobox({})
    car_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        url: "/carInformation/getAll.do",
        pagination: true,
        singleSelect: true,
        rownumbers: true,
        columns: [[
            {field: 'brand', title: '品牌', width: 100},
            {field: 'version', title: '型号', width: 100},
            {field: 'gasnumber', title: '排气量', width: 100},
            {field: 'price', title: '估值', width: 100},
            {
                field: 'type', title: '汽车分类', width: 100,
                formatter: function (value) {
                    return value ? "<font color='blue'>载客</font>" : "<font color='red'>载物</font>"
                }
            },
            {
                field: 'size', title: '大小', width: 100,
                formatter: function (value, row, index) {
                    if (value == 0 && value == '') {
                        return "小型";
                    } else if (value == 1) {
                        return "中型";
                    } else if (value == 2) {
                        return "大型";
                    } else {
                        return "超大型";
                    }
                }
            }
        ]],
        onDblClickRow: function () {
            sure_car();
        }
    });

    //机构
    var organization_select = $("#organization_select");
    organization_select.combogrid({
        url: '/organization/getAll.do',
        panelWidth: 450,
        value: '请选择',
        idField: 'name',
        textField: 'name',
        columns: [[
            {field: 'id', title: '机构编号', width: 50},
            {field: 'sn', title: '机构代码', width: 100},
            {field: 'name', title: '机构名称', width: 100},
            {field: 'legalperson', title: '法人代表', width: 100},
            {field: 'identity', title: '法人身份证', width: 100},
            {field: 'tel', title: '', width: 100},
            {field: 'address', title: '联系地址', width: 100},
            {
                field: 'state', title: '合作关系', width: 100,
                formatter: function (value) {
                    return value ? "<font color='blue'>是</font>" : "<font color='red'>否</font>"
                }
            }
        ]],
        onChange: function () {
            var hiddens = $(".product-tr");
            $.each(hiddens, function (index, item) {
                if (index != 0) {
                    $(item).remove();
                }
            });
            $("#totalAmount").html(0);
        }
    })

    //选择产品
    var choose_product_dialog = $("#choose_product_dialog");
    var product_datagrid = $("#product_datagrid");
    choose_product_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#product_btns2',
        closed: true,
        modal: true
    });
    product_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        toolbar: '#product_toolbar',
        url: "/product/getAll.do",
        pagination: true,
        rownumbers: true,
        ctrlSelect: true,
        singleSelect: true,
        columns: [[
            {field: 'sn', title: '产品编号', width: 100},
            {field: 'name', title: '产品名称', width: 100},
            {field: 'organization', title: '机构名称', width: 100},
            {
                field: 'organization', title: '机构名称', width: 100,
                formatter: function (value) {
                    return value ? value.name : '';
                }
            },
            {field: 'year', title: '保障年限', width: 100},
            {field: 'coverage', title: '保额', width: 100},
            {field: 'cost', title: '基本年费', width: 100},
            {
                field: 'state', title: '销售状态', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>在售</font>" : "<font color='red'>停售</font>"
                }
            },
            {
                field: 'franchies', title: '不计免赔', width: 100,
                formatter: function (value) {
                    return value ? "<font color='blue'>是</font>" : "<font color='red'>否</font>"
                }
            }
        ]]
    });


    var methodObject;
    methodObject = {
        //弹出选择客户窗口
        choose_customer: function () {
            choose_customer_dialog.dialog("setTitle", "请选择客户");
            choose_customer_dialog.dialog("open");
        },

        //选择客户
        select_customer: function () {
            sure_customer();
        },

        //选择汽车
        choose_car: function () {
            choose_car_dialog.dialog("setTitle", "请选择车型");
            choose_car_dialog.dialog("open")
        },
        select_car: function () {
            sure_car();
        },


        //添加产品
        add_product: function () {
            var organizationName = $("#organization_select").combobox("getValue");
            if (organizationName == "请选择" || organizationName == null || organizationName == '') {
                $.messager.alert('温馨提示', ' 请选择承保机构！', "warning");
                return;
            }
            choose_product_dialog.dialog("open");
            choose_product_dialog.dialog("setTitle", "请选择保险产品");
            $.post("/product/listAll.do", {organizationName: organizationName, state: true}, function (data) {
                product_datagrid.datagrid("loadData", data);
            });
        },
        //选择产品，计算总金额
        select_product: function () {
            //添加所有选中的产品到列表中
            var product = product_datagrid.datagrid("getSelected");
            /* //获取已有产品的id
             var oids = $.map($(".product-tr"), function (item, index) {
                 return $(item).attr("data-oid");
             });*/
            if (product != null) {
                //插入产品
                $("#hidethis").attr("data-oid", product.id);
                $("#hidethis").find("#productName").html(product.name);
                $("#hidethis").find("#productSn").html(product.sn);
                $("#hidethis").find("#cost").html(product.cost);
                /* $.each(products, function (index, item) {
                     if ($.inArray(item.id + "", oids) == -1) {
                         var clone = $("#hidethis").clone(true);
                         clone.show();
                         clone.
                         attr("data-oid", item.id);
                         clone.find("#productName").html(item.name);
                         clone.find("#productSn").html(item.sn);
                         clone.find("#cost").html(item.cost);
                         clone.insertAfter($("#hidethis"));
                     }
                 });*/
                //计算总金额
                calculate();
            }
            //关闭弹窗
            choose_product_dialog.dialog("close");
        }
    }

    //触发点击函数
    $("[data-cmd]").click(function () {
        methodObject[$(this).data("cmd")]();
    });
});

//选择客户
function sure_customer() {
    var customer = $("#customer_datagrid").datagrid("getSelected");
    $("[name='customer.id']").val(customer.id);
    $("[name='customer.idcard']").val(customer.idcard);
    $("[name='customer.tel']").val(customer.tel);
    $("#address").textbox("setValue", customer.address);
    $("[name='customer.name']").val(customer.name);
    $("#customer_gender").combobox("setValue", customer.gender);
    $("#choose_customer_dialog").dialog("close");
}

//选择汽车
function sure_car() {
    var car = $("#car_datagrid").datagrid("getSelected");
    $("#car_id").val(car.id);
    $("#carbrand").textbox("setValue", car.brand);
    $("#carversion").textbox("setValue", car.version);
    $("#gasnumber").textbox("setValue", car.gasnumber);
    $("#cartype").combobox("setValue", car.type);
    $("#carsize").combobox("setValue", car.size);
    $("#price").textbox("setValue", car.price);
    $("#choose_car_dialog").dialog("close");
}


//计算总金额
function calculate() {
    var totalAmount = 0;
    $.each($(".cost"), function (index, item) {
        if (parseInt(item.innerHTML)) {
            totalAmount = totalAmount + parseInt(item.innerHTML);
        }
    })
    var burningTime = 0
    if ($("[name=burningTime]").val()) {
        burningTime = $("[name=burningTime]").val();
    }
    $("#totalAmount").html(totalAmount * burningTime);

}

//删除产品
function delete_this(data) {
    $(data).closest("#hidethis").remove();
    calculate();
}

//暂存
function tempStor_submit() {
    $("#form").form("submit", {
        url: '/insurance/saveOrUpdate.do',
        onSubmit: function (param) {
            param['product.id'] = $("#hidethis").attr("data-oid");
            param.totalAmount = $("#totalAmount").html();
            param.state = 1;
        },
        success: function (data) {
            data = $.parseJSON(data)
            if (!data.success) {
                $.messager.alert("保单暂存失败", data.msg, "error");
            } else {
                $.messager.alert("保单已提审", data.msg, "info", function () {
                    $("#form").form('clear');
                });
            }
        }
    });
}

//提审
function preAudit_submit() {
    $("#form").form("submit", {
        url: '/insurance/saveOrUpdate.do',
        onSubmit: function (param) {
            param['product.id']= $("#hidethis").attr("data-oid");
            param.totalAmount = $("#totalAmount").html();
            param.state = 3;
        },
        success: function (data) {
            data = $.parseJSON(data)
            if (!data.success) {
                $.messager.alert("保单暂存失败", data.msg, "error");
            } else {
                $.messager.alert("保单已提审", data.msg, "info", function () {
                    $("#form").form('clear');
                });
            }
        }
    });
}